<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <div slot="after">
          <el-button type="primary" size="small" @click="$router.push('/import')">导入</el-button>
          <el-button type="primary" size="small" @click="exportData">导出</el-button>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addBtn">新增员工</el-button>
        </div>
      </PageTools>
      <el-card>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="150"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="120"
            sortable=""
          />
          <el-table-column
            label="头像"
            width="140"
            align="center"
          >
            <template slot-scope="{row}">
              <img
                v-imageerror="defaultImg"
                :src="row.staffPhoto"
                alt=""
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            width="120"
            sortable=""
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            width="120"
            sortable=""
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            width="250"
            :formatter="isTimeOfEntry"
            sortable=""
          />
          <el-table-column
            prop="departmentName"
            label="部门"
            width="120"
            sortable=""
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            width="120"
            sortable=""
          >
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatTimeOfEntry }}
            </template>
          </el-table-column>
          <el-table-column
            prop="inServiceStatus"
            label="是否在职"
            width="120"
            sortable=""
            :formatter="isInServiceStatus"
          />
          <el-table-column
            prop="enableState"
            label="状态"
            width="120"
            sortable=""
          >
            <template slot-scope="{row}">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column
            min-width="240"
            fixed="right"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleClick(scope.row)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="rolePermission(scope.row.id)">角色</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <span class="demonstration">共{{ page.total }}条</span>
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            :current-page="page.page"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" :title="title" />
      <el-dialog :visible.sync="showCanvas" title="二维码">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色 -->
      <assignRole :show-role-dialog.sync="showRole" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList } from '@/api/employees'
import employees from '@/api/constant/employees'
import moment from 'moment'
import addEmployee from './components/add-employee.vue'
import { getUserDetailById } from '@/api/user'
import qrcode from 'qrcode'
import assignRole from './components/assign-role.vue'
export default {
  filters: {
    formatTimeOfEntry(val) {
      // console.log(val)
      return moment(val).format('YYYY-MM-DD')
    }
  },
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      tableData: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      showDialog: false,
      title: '',
      defaultImg: require('@/assets/common/head.jpg'),
      showCanvas: false,
      showRole: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async handleClick(row) {
      const result = await getUserDetailById(row.id)
      this.$router.push({
        path: `/employees/detail/${row.id}`,
        query: result
      })
    },
    addBtn() {
      this.title = '新增员工'
      this.showDialog = true
    },
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.page)
      // console.log(total)
      this.page.total = total
      // console.log(rows)
      this.tableData = rows
      // console.log(rows)
    },
    changePage(newPage) {
      // console.log(newPage)
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    isTimeOfEntry(row, column, cellValue, index) {
      const obj = employees.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 格式化是否在职
    isInServiceStatus(row, column, cellValue, index) {
      const obj = employees.workingState.find(item => item.id === (cellValue + ''))
      return obj ? obj.value : '未知'
    },
    // 导出Excel表
    exportData() {
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        // console.log([...Object.keys(headers)])
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        const { rows } = await getEmployeeList(this.page)
        const data = this.formatJson(rows, headers)
        // console.log(data)
        // console.log(rows)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          multiHeader,
          merges
        })
      })
    },
    formatJson(rows, headers) {
      const data = []
      rows.forEach(obj => {
        const arr = Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            const temp = this.$options.filters['formatTimeOfEntry']
            // console.log(temp(obj[headers[key]]))
            return temp(obj[headers[key]]) === 'Invalid date' ? '未知' : temp(obj[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj1 = employees.hireType.find(item => item.id === obj[headers[key]])
            return obj1.value || '未知'
          }
          return obj[headers[key]]
        })
        data.push(arr)
      })
      return data
    },
    showQrCode(url) {
      if (url) {
        this.showCanvas = true
        this.$nextTick(() => {
          qrcode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户没有上传头像')
      }
    },
    rolePermission(id) {
      this.showRole = true
      this.userId = id
    }
  }
}
</script>

<style>

</style>
